package cn.dakaqi.services.user.impl;

import cn.dakaqi.dao.user.VolunteerWelfareDao;
import cn.dakaqi.entities.Welfare;
import cn.dakaqi.entities.WelfareItem;
import cn.dakaqi.entities.user.VolunteerWelfare;
import cn.dakaqi.services.WelfareItemService;
import cn.dakaqi.services.WelfareService;
import cn.dakaqi.services.user.VolunteerWelfareService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by chunyang on 2016/4/18.
 */
@Component(value = "volunteerWelfareService")
@Transactional
public class VolunteerWelfareServiceImpl implements VolunteerWelfareService
{
    @Autowired
    VolunteerWelfareDao volunteerWelfareDao;
    @Autowired
    WelfareService welfareService;
    @Autowired
    WelfareItemService welfareItemService;

    @Override
    public void save(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String memberCode = jsonObject.getString("memberCode");
        Long welfareId = jsonObject.getLong("welfareId");
        Welfare welfare = welfareService.findOne(welfareId);

        if(null == welfare)
            throw  new ServiceRuntimeException("当前福利无效");

        Float price = welfare.getPrice();//价格
        String specialDemo = welfare.getSpecialDemo();//'特殊说明',
        String startDay = welfare.getStartDay();// '开始日期、',
        String endDay = welfare.getEndDay();//'结束日期',
        String useDemo = welfare.getUseDemo();//'使用说明',
        int times = welfare.getTimes();//'兑换条件公益时间',
        int integral = welfare.getIntegral();//'兑换所需积分',
        String useAndroid = welfare.getUseAndroid();//'安卓是否立即使用(0不使用1使用)',
        String androidPackage = welfare.getAndroidPackage();//'android使用地址',
        String androidUrl = welfare.getAndroidUrl();//
        String useIos = welfare.getUseIos();//'苹果是否立即使用(0不使用 1使用)',
        String iosAddres = welfare.getIosAddres();//'ios使用地址',
        String useWeb = welfare.getUseWeb();//'网页是否立即使用(0不使用 1使用)',
        String webAddress = welfare.getWebAddress();//'网页使用地址',
        String img= welfare.getImg(); //'封面图',
        String name = welfare.getName();

        VolunteerWelfare volunteerWelfare = new VolunteerWelfare();
        volunteerWelfare.setMemberCode(memberCode);
        volunteerWelfare.setTimes(times);
        volunteerWelfare.setPrice(price);
        volunteerWelfare.setSpecialDemo(specialDemo);
        volunteerWelfare.setStartDay(startDay);
        volunteerWelfare.setEndDay(endDay);
        volunteerWelfare.setUseDemo(useDemo);
        volunteerWelfare.setIntegral(integral);
        volunteerWelfare.setUseAndroid(useAndroid);
        volunteerWelfare.setAndroidPackage(androidPackage);
        volunteerWelfare.setAndroidUrl(androidUrl);
        volunteerWelfare.setUseIos(useIos);
        volunteerWelfare.setIosAddres(iosAddres);
        volunteerWelfare.setUseWeb(useWeb);
        volunteerWelfare.setWebAddress(webAddress);
        volunteerWelfare.setImg(img);
        volunteerWelfare.setName(name);
        volunteerWelfare.setCreateTime(Clock.DEFAULT.getCurrentDate());
        save(welfare,volunteerWelfare);
    }

    @Override
    public void save(Welfare welfare,VolunteerWelfare volunteerWelfare) throws ServiceRuntimeException
    {
        //检查当前福利可领取数量
        WelfareItem welfareItem = this.welfareItemService.findUnChangeByWelfare(welfare.getId());
        if(null == welfareItem)
            throw new ServiceRuntimeException("福利已领完,下次早点过来吧!");

        //检查当前福利每人可兑换的数量
        int exchangeCounts = Integer.parseInt(welfare.getExchangeCounts());
        List<WelfareItem> itemList = this.welfareItemService.findByMemberAndWelfare(volunteerWelfare.getMemberCode(),welfare.getId());
        if(null != itemList && itemList.size()>=exchangeCounts)
            throw new ServiceRuntimeException("当前福利每人仅可兑换"+exchangeCounts+"次");
        //更新当前福利的领取状态
        welfareItem.setIsChanage(DKQConstant.WELFARE_ITEM_CHANGE);
        welfareItem.setMemberCode(volunteerWelfare.getMemberCode());
        this.welfareItemService.update(welfareItem);

        //生成领取订单数据
        this.volunteerWelfareDao.save(volunteerWelfare);
        //修改当前福利已兑换的数量
        welfare.setHasExchanges(welfare.getHasExchanges()+1);
        welfareService.update(welfare);
    }

    @Override
    public Page<VolunteerWelfare> findByVolunteer(String memberCode, int pageNumber) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("memberCode", new SearchFilter("memberCode", SearchFilter.Operator.EQ, memberCode));
        Specification<VolunteerWelfare> spec = DynamicSpecifications.bySearchFilter(filters.values(), VolunteerWelfare.class);
        return this.volunteerWelfareDao.findAll(spec, pageRequest);
    }

    @Override
    public VolunteerWelfare findOne(Long id) throws ServiceRuntimeException
    {
        return volunteerWelfareDao.findOne(id);
    }
}
